package com.astersoft.lib.cypher.crypt.impl;

/*
 * Copyright 2012 AsterSoft personal developer - Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import com.astersoft.lib.cypher.codec.Base64;
import com.astersoft.lib.cypher.crypt.Encryptable;

/**
 * A DES implementation of the Encryptable interface.
 * With this class we can provide DES cypher
 * 
 * <p>
 * This class is used to encode and decode file using the DES
 * encryption algorithm
 * <p>
 * 
 * @see Encryptable
 * 
 * @author dario durzo
 * @version 0.1
 * @date 29-05-2012
 */
public class DESEncrypter 
implements Encryptable {
	
	// internal cyphers
	private Cipher ecipher;
    private Cipher dcipher;

    // 8-byte Salt
    private byte[] salt = {
        (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
        (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
    };
    
    // Buffer used to transport the bytes from one stream to another
    private byte[] buf = new byte[1024];

    // Iteration count
    private final int iterationCount = 19;
    
    /**
     * Initialize the cypher algorithm
     * 
     * @param passPhrase 
     * 				the String key
     */
	@Override
	public void initCypher(String passPhrase) {
		try {
            // Create the key
            KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
            SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
            ecipher = Cipher.getInstance(key.getAlgorithm());
            dcipher = Cipher.getInstance(key.getAlgorithm());

            // Prepare the parameter to the ciphers
            AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

            // Create the ciphers
            ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
            dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        } catch (java.security.InvalidAlgorithmParameterException e) {
        } catch (java.security.spec.InvalidKeySpecException e) {
        } catch (javax.crypto.NoSuchPaddingException e) {
        } catch (java.security.NoSuchAlgorithmException e) {
        } catch (java.security.InvalidKeyException e) {
        }
	}

	@Override
	public void encrypt(InputStream in, OutputStream out) {
		try {
            // Bytes written to out will be encrypted
            out = new CipherOutputStream(out, ecipher);

            // Read in the cleartext bytes and write to out to encrypt
            int numRead = 0;
            while ((numRead = in.read(buf)) >= 0) {
                out.write(buf, 0, numRead);
            }
            out.close();
        } catch (java.io.IOException e) {
        }
	}

	@Override
	public void decrypt(InputStream in, OutputStream out) {
		try {
            // Bytes read from in will be decrypted
            in = new CipherInputStream(in, dcipher);

            // Read in the decrypted bytes and write the cleartext to out
            int numRead = 0;
            while ((numRead = in.read(buf)) >= 0) {
                out.write(buf, 0, numRead);
            }
            out.close();
        } catch (java.io.IOException e) {
        }
	}

	@Override
	public String encrypt(String input) {
		try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = input.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new String(Base64.encode(enc));
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        }
        return null;
	}

	@Override
	public String decrypt(String input) {
		try {
            // Decode base64 to get bytes
            byte[] dec = Base64.decode(input);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        }
        return null;
	}
	
	/**
	 * Main test point
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args)
	throws Exception {
		DESEncrypter en = new DESEncrypter();
		en.initCypher("pippononlosa");
		String input = "ciaoMondo!";
		String output;
		output = en.encrypt(input);
		System.out.println("encrypt = " + output);
		output = en.decrypt(output);
		System.out.println("encrypt = " + output);
	}
}
